package com.orchid.community.models.service.impl;

import com.orchid.community.common.exceptions.CustomException;
import com.orchid.community.common.utils.CodeEnum;
import com.orchid.community.common.utils.MD5Util;
import com.orchid.community.common.utils.MsgResponse;
import com.orchid.community.common.utils.ResultUtils;
import com.orchid.community.models.DTO.LoginRequestDTO;
import com.orchid.community.models.entity.SysUsers;
import com.orchid.community.models.mapper.SysUsersMapper;
import com.orchid.community.models.service.SysUsersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service
@Slf4j
public class SysUsersServiceImpl implements SysUsersService {

    @Autowired
    private SysUsersMapper sysUsersMapper;

    @Override
    public MsgResponse login(SysUsers user) {
        String username = user.getUsername();
        String userPassword = user.getPassword();
        //对密码进行加密
        String password = MD5Util.MD5(userPassword);
        //判断用户是否存在
        SysUsers userInfo = sysUsersMapper.getByUsernameAdnPassword(username, password);
        if(null == userInfo){
            return ResultUtils.fail("账号或密码错误，请重新输入!");
        }
        //判断用户是否被冻结
        if(userInfo.getFreeze() == 1){
            return ResultUtils.fail("该用户已被冻结，请联系管理员!");
        }
        //判断是否被删除
        log.info("用户信息====:{}",userInfo);
        if(userInfo.getStatus() == 1){
            return ResultUtils.fail(CodeEnum.DATA_ERROR);
        }
        //生成token
        String token = MD5Util.MD5(userInfo.getSysUserId().toString() + userInfo.getUsername() + System.currentTimeMillis());
        try {
            sysUsersMapper.updateToken(userInfo.getUsername(),token);
        } catch (Exception e) {
            log.error("更新token失败:{}",e.getMessage());
            throw new CustomException(CodeEnum.DATA_ERROR);
        }

        LoginRequestDTO loginRequest = new LoginRequestDTO();

        String permission = userInfo.getPermission();
        if(permission != null){
            loginRequest.setPermission(Arrays.asList(permission.split(",")));
        }
        loginRequest.setSysUserId(userInfo.getSysUserId());
        loginRequest.setRole(String.valueOf(userInfo.getUserRole()));
        loginRequest.setToken(token);
        loginRequest.setName(userInfo.getName());
        return ResultUtils.success(loginRequest);
    }

    @Override
    public MsgResponse deleteTokenById(Integer id) {
        sysUsersMapper.deleteTokenById(id);
        return ResultUtils.success();
    }
}
